//demo16.cpp多进程的生产消费者模型——生产者

#include "public13.h"

int main()
{
    struct People
    {
        int age;
        char name[51];
    };

    using ElemType = People;

    //初始化共享内存
    int shmid = shmget(0X5005, sizeof(squeue<ElemType, 5>), 0640|IPC_CREAT);
    if(shmid == -1)
    {
        cout << "shmget(0x5005) failed. " << endl;
        return -1;
    }

    //把共享内存连接到当前进程的地址空间
    squeue<ElemType, 5> *QQ = (squeue<ElemType, 5> *)shmat(shmid, 0, 0);        //队列容量为5
    if(QQ == (void *)-1)
    {
        cout << "shmat() failed. " << endl;
    }

    QQ->init();

    ElemType ee;

    csemp mutex; mutex.init(0x5001);            //互斥锁
    csemp cond; cond.init(0x5002, 0, 0);        //条件变量

    mutex.wait();       //加锁
    //生产3个数据
    ee.age = 20; strcpy(ee.name, "张三"); QQ->push(ee);
    ee.age = 19; strcpy(ee.name, "李四"); QQ->push(ee);
    ee.age = 21; strcpy(ee.name, "王五"); QQ->push(ee);

    mutex.post();       //解锁
    cond.post(3);       //实参为3，表示生产力3个数据

    shmdt(QQ);  //把共享内存从当前进程中分离
}
